const express = require('express')
const multer = require('multer')
const { UPLOAD_PATH } = require('../utils/constant')
const Result = require('../models/Result')
const Book = require('../models/Book')
const boom = require('boom')
const { decoded } = require('../utils')
const resumeService = require('../services/resume')
const Resume = require('../models/Resume')
const router = express.Router()
//获取新闻列表
router.get('/ResumeList', function(req, res) {
    resumeService.ResumeList().then(Resume => {
            if (Resume) {

                new Result(Resume, '新闻信息查询成功').success(res)
            } else {
                new Result('新闻信息查询失败').fail(res)
            }
        })

})


//添加新闻图片
router.post('/uploadResume', multer({ dest: `${UPLOAD_PATH}/resume` }).single('file'),function(req, res, next) {
        console.log(req.file)
        console.log(req.body)
        //const resume = req.file
        if (!req.file || req.file.length === 0) {
            new Result('上传图片失败').fail(res)
        } else {
            const resumeImg = new Resume(req.file)
            //因为上传的文件没有jpg的图片后缀，所有加一个parse（）来重命名
            resumeImg.parse()
                .then(resumeImg => {
                    //new Result(resumeImg, '上传图片成功').success(res)
                })
                .catch(err => {
                    next(boom.badImplementation(err))
                })
            const resume = new Resume(null,req.body)
            resumeService.insertResume(resume.toDb()).then(() => {
                new Result('添加用户成功').success(res)
            }).catch(err => {
                next(boom.badImplementation(err))
            })
        }




    }
)
//添加新闻
router.post('/createResume', function(req, res, next) {
        console.log(req.body)
        const resume = req.body
        resumeService.insertResume(resume).then(() => {
            new Result('添加用户成功').success(res)
        }).catch(err => {
            next(boom.badImplementation(err))
        })
    }
)

//修改新闻
router.post('/updateResume', function(req, res, next) {
        console.log(req.body)
        const resume = req.body
        resumeService.updateResume(resume).then(() => {
            new Result('修改新闻成功').success(res)
        }).catch(err => {
            next(boom.badImplementation(err))
        })
    }
)
//删除新闻
router.post('/deleteResume', function(req, res, next) {

    const id = req.body.id
    if (!id) {
        next(boom.badRequest(new Error('参数id不能为空')))
    } else {
        resumeService.deleteResume(id).then(() => {
            new Result('删除新闻信息成功').success(res)
        }).catch(err => {
            next(boom.badImplementation(err))
        })
    }
})


module.exports = router
